import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/control_room/user_room.dart';
import 'package:thal/backstage/control_room/dynamic_room.dart';
import 'package:thal/backstage/control_room/follow_room.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/toolkit/widgets/authentication_focus_curtain.dart';
import 'package:thal/backstage/toolkit/widgets/report_focus_curtain.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:thal/playbill/community_forum/video_play_production.dart';
import 'package:thal/playbill/profile_saga/other_profile_production.dart';

part 'dynamic_production.page.dart';

/// 动态详情页面
@PagePath('/dynamic/:dynamicId')
class DynamicProduction extends StatefulWidget {
  final String dynamicId;

  const DynamicProduction({super.key, required this.dynamicId});

  @pageRouteQuery
  static RouteQuery query({required String dynamicId}) =>
      _$DynamicProductionQuery().call(dynamicId: dynamicId);

  @override
  State<DynamicProduction> createState() => _DynamicProductionState();
}

class _DynamicProductionState extends State<DynamicProduction> {
  late UserRoom _userRoom;
  late DynamicRoom _dynamicRoom;
  late FollowRoom _followRoom;
  int _currentMediaIndex = 0;
  final TextEditingController _commentController = TextEditingController();

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _userRoom = GlobalStateProvider.userRoomOf(context);
    _dynamicRoom = GlobalStateProvider.dynamicRoomOf(context);
    _followRoom = GlobalStateProvider.followRoomOf(context);
  }

  @override
  void dispose() {
    _commentController.dispose();
    super.dispose();
  }

  /// 获取当前动态
  _DynamicData? _getCurrentDynamic() {
    final dynamicPrint = _dynamicRoom.fetchDynamicById(widget.dynamicId);
    if (dynamicPrint == null) return null;

    final author = _userRoom.fetchUserById(dynamicPrint.userId);

    return _DynamicData(
      id: dynamicPrint.id,
      userId: dynamicPrint.userId,
      title: dynamicPrint.title,
      content: dynamicPrint.content,
      mediaUrls: dynamicPrint.mediaUrls,
      mediaType: dynamicPrint.mediaType,
      thumbnailUrls: dynamicPrint.thumbnailUrls,
      createdAt: dynamicPrint.createdAt,
      likes: dynamicPrint.likes,
      comments: dynamicPrint.comments,
      authorName: author?.username ?? 'Unknown',
      authorAvatar: author?.avatar ?? '',
    );
  }

  /// 构建固定标题栏
  Widget _buildFixedHeader() {
    return Container(
      height: 60.h,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left_rounded,
                color: ColorPalette.black,
                size: 36.sp,
              ),
            ),
          ),
          // 举报按钮
          GestureDetector(
            onTap: _handleReport,
            child: Container(
              width: 40.w,
              height: 40.w,
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Image.asset(
                AssetManifest.report2,
                width: 24.w,
                height: 24.w,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建媒体轮播
  Widget _buildMediaCarousel() {
    final dynamic = _getCurrentDynamic();
    if (dynamic == null) return SizedBox.shrink();

    final hasMultipleMedia = dynamic.mediaUrls.length > 1;

    return Column(
      children: [
        AspectRatio(
          aspectRatio: 358 / 448,
          child: Stack(
            children: [
              Swiper(
                itemBuilder: (BuildContext context, int index) {
                  final mediaUrl =
                      dynamic.mediaType == 'video'
                          ? (dynamic.thumbnailUrls.isNotEmpty &&
                                  dynamic.thumbnailUrls[index] != null
                              ? dynamic.thumbnailUrls[index]!
                              : dynamic.mediaUrls[index])
                          : dynamic.mediaUrls[index];

                  return GestureDetector(
                    onTap:
                        dynamic.mediaType == 'video'
                            ? () {
                              context.router.push(
                                VideoPlayProduction.query(
                                  dynamicId: dynamic.id,
                                  mediaIndex: index,
                                ),
                              );
                            }
                            : null,
                    child: Container(
                      margin: EdgeInsets.symmetric(horizontal: 16.w),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(16.r),
                        image: DecorationImage(
                          image: AssetImage(mediaUrl),
                          fit: BoxFit.cover,
                        ),
                      ),
                      child:
                          dynamic.mediaType == 'video'
                              ? Center(
                                child: Icon(
                                  Icons.play_arrow_rounded,
                                  size: 60.w,
                                  color: ColorPalette.white,
                                ),
                              )
                              : null,
                    ),
                  );
                },
                itemCount: dynamic.mediaUrls.length,
                loop: false,
                onIndexChanged:
                    hasMultipleMedia
                        ? (index) {
                          setState(() {
                            _currentMediaIndex = index;
                          });
                        }
                        : null,
              ),
              // 指示器
              if (hasMultipleMedia)
                Positioned(
                  top: 16.h,
                  left: 76.w,
                  right: 76.w,
                  child: Row(
                    children: List.generate(
                      dynamic.mediaUrls.length,
                      (index) => Expanded(
                        child: Padding(
                          padding: EdgeInsets.only(
                            right:
                                index < dynamic.mediaUrls.length - 1 ? 4.w : 0,
                          ),
                          child: AnimatedContainer(
                            duration: Duration(milliseconds: 200),
                            height: 3.h,
                            decoration: BoxDecoration(
                              color:
                                  _currentMediaIndex == index
                                      ? ColorPalette.white
                                      : ColorPalette.white.withValues(
                                        alpha: 0.5,
                                      ),
                              borderRadius: BorderRadius.circular(2.r),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建动态详情卡片
  Widget _buildDynamicDetailsCard() {
    final dynamic = _getCurrentDynamic();
    if (dynamic == null) return SizedBox.shrink();

    final currentUser = _userRoom.fetchCurrentUser();
    final isOwnPost = currentUser != null && currentUser.id == dynamic.userId;

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: ColorPalette.white,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: [
          BoxShadow(
            color: ColorPalette.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: Offset(0, 2.h),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text(dynamic.title)
              .fontSize(18.sp)
              .textColor(ColorPalette.black)
              .arimo(weight: FontWeight.w400),
          16.h.heightBox,
          // 内容
          Text(
            dynamic.content,
            style: TextStyle(
              fontSize: 14.sp,
              color: ColorPalette.black.withValues(alpha: 0.78),
              height: 1.6,
            ),
          ).arimo(weight: FontWeight.w400),
          20.h.heightBox,
          // 发布者信息和操作按钮
          Row(
            children: [
              // 头像
              GestureDetector(
                onTap:
                    isOwnPost
                        ? null
                        : () {
                          // 跳转到他人主页
                          context.router.push(
                            OtherProfileProduction.query(
                              userId: dynamic.userId,
                            ),
                          );
                        },
                child: Container(
                  width: 40.w,
                  height: 40.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    image: DecorationImage(
                      image: AssetImage(dynamic.authorAvatar),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),
              12.w.widthBox,
              // 用户名和时间
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(dynamic.authorName)
                      .fontSize(14.sp)
                      .textColor(ColorPalette.black)
                      .arimo(weight: FontWeight.w600),
                  2.h.heightBox,
                  Text(_formatRelativeTime(dynamic.createdAt))
                      .fontSize(12.sp)
                      .textColor(ColorPalette.black.withValues(alpha: 0.5))
                      .arimo(weight: FontWeight.w400),
                ],
              ),
              Spacer(),
              // 关注按钮
              Observer(
                builder: (context) {
                  final currentUser = _userRoom.fetchCurrentUser();
                  final isFollowing =
                      currentUser != null &&
                      _followRoom.isFollowing(currentUser.id, dynamic.userId);

                  return SizedBox(
                    width: 73.w,
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 5.h),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color:
                            isFollowing
                                ? ColorPalette.blue1
                                : ColorPalette.white,
                        borderRadius: BorderRadius.circular(25.r),
                        border: Border.all(
                          color:
                              isFollowing
                                  ? ColorPalette.blue1
                                  : const Color(0x30999999),
                          width: 1.w,
                        ),
                      ),
                      child: Text(
                        isFollowing ? 'Folloed' : 'Follow',
                        style: TextStyle(
                          color:
                              isFollowing
                                  ? ColorPalette.white
                                  : ColorPalette.black,
                        ),
                      ).fontSize(14.sp).arimo(weight: FontWeight.w700),
                    ),
                  ).withTapEffect(onTap: () => _handleFollow(dynamic.userId));
                },
              ),
              8.w.widthBox,
              // 点赞按钮
              Observer(
                builder: (context) {
                  final currentUser = _userRoom.fetchCurrentUser();
                  final isLiked =
                      currentUser != null &&
                      _dynamicRoom.isLikedByUser(dynamic.id, currentUser.id);
                  // 获取最新的动态数据以获取正确的点赞数
                  final latestDynamic = _dynamicRoom.fetchDynamicById(
                    dynamic.id,
                  );

                  return SizedBox(
                    width: 73.w,
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 5.h),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: ColorPalette.white,
                        borderRadius: BorderRadius.circular(25.r),
                        border: Border.all(
                          color:
                              isLiked
                                  ? ColorPalette.pink
                                  : const Color(0x30999999),
                          width: 1.w,
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Image.asset(
                            isLiked ? AssetManifest.like : AssetManifest.unlike,
                            width: 16.w,
                            height: 16.w,
                            color:
                                isLiked ? ColorPalette.pink : ColorPalette.pink,
                          ),
                          4.w.widthBox,
                          Text('${latestDynamic?.likes.length ?? 0}')
                              .fontSize(14.sp)
                              .textColor(
                                isLiked
                                    ? ColorPalette.black
                                    : ColorPalette.black,
                              )
                              .arimo(weight: FontWeight.w700),
                        ],
                      ),
                    ),
                  ).withTapEffect(onTap: () => _handleLike(dynamic.id));
                },
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建评论列表
  Widget _buildCommentsList() {
    return Observer(
      builder: (context) {
        // 直接访问 dynamics 列表以确保响应式更新
        try {
          final latestDynamic = _dynamicRoom.dynamics.firstWhere(
            (d) => d.id == widget.dynamicId,
          );

          return Container(
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: ColorPalette.white,
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text.rich(
                  TextSpan(
                    children: [
                      TextSpan(
                        text: 'There are a total of ',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: ColorPalette.black.withValues(alpha: 0.6),
                          fontWeight: FontWeight.w400,
                          fontFamily: 'Arimo',
                        ),
                      ),
                      TextSpan(
                        text: '${latestDynamic.comments.length}',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: ColorPalette.black,
                          fontWeight: FontWeight.w700,
                          fontFamily: 'Arimo',
                        ),
                      ),
                      TextSpan(
                        text: ' comments',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: ColorPalette.black.withValues(alpha: 0.6),
                          fontWeight: FontWeight.w400,
                          fontFamily: 'Arimo',
                        ),
                      ),
                    ],
                  ),
                ),
                16.h.heightBox,
                if (latestDynamic.comments.isEmpty)
                  Padding(
                    padding: EdgeInsets.all(32.w),
                    child: Center(
                      child: Text('No comments yet')
                          .fontSize(14.sp)
                          .textColor(ColorPalette.black.withValues(alpha: 0.5))
                          .arimo(weight: FontWeight.w400),
                    ),
                  )
                else
                  ...latestDynamic.comments.asMap().entries.map((entry) {
                    final index = entry.key;
                    final comment = entry.value;
                    final commenter = _userRoom.fetchUserById(comment.userId);
                    return _buildCommentItem(
                      comment,
                      commenter,
                      index < latestDynamic.comments.length - 1,
                    );
                  }),
              ],
            ),
          );
        } catch (e) {
          return SizedBox.shrink();
        }
      },
    );
  }

  /// 构建单个评论项
  Widget _buildCommentItem(dynamic comment, user, bool hasBottomBorder) {
    final currentUser = _userRoom.fetchCurrentUser();
    final isOwnComment =
        currentUser != null && currentUser.id == comment.userId;

    return Column(
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 评论者头像
            GestureDetector(
              onTap:
                  isOwnComment
                      ? null
                      : () {
                        // 跳转到他人主页
                        context.router.push(
                          OtherProfileProduction.query(userId: comment.userId),
                        );
                      },
              child: Container(
                width: 44.w,
                height: 44.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  image: DecorationImage(
                    image: AssetImage(user?.avatar ?? ''),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
            12.w.widthBox,
            // 评论内容
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(user?.username ?? 'Unknown')
                          .fontSize(14.sp)
                          .textColor(ColorPalette.black)
                          .arimo(weight: FontWeight.w700),
                      8.w.widthBox,
                      Text(_formatCommentDate(comment.createdAt))
                          .fontSize(12.sp)
                          .textColor(ColorPalette.black.withValues(alpha: 0.5))
                          .arimo(weight: FontWeight.w400),
                    ],
                  ),
                  8.h.heightBox,
                  Text(comment.content)
                      .fontSize(14.sp)
                      .textColor(ColorPalette.black.withValues(alpha: 0.78))
                      .arimo(weight: FontWeight.w400),
                ],
              ),
            ),
            8.w.widthBox,
            // 举报图标
            GestureDetector(
              onTap: () => _handleReportComment(comment.id),
              child: Container(
                width: 24.w,
                height: 24.w,
                decoration: BoxDecoration(shape: BoxShape.circle),
                child: Center(
                  child: Image.asset(
                    AssetManifest.report3,
                    width: 20.w,
                    height: 20.w,
                  ),
                ),
              ),
            ),
          ],
        ),
        // 底部分隔线（除了最后一条）
        if (hasBottomBorder) ...[
          16.h.heightBox,
          Container(height: 1.h, color: ColorPalette.grey),
          16.h.heightBox,
        ],
      ],
    );
  }

  /// 构建底部评论输入框
  Widget _buildCommentInput() {
    return SizedBox(
      height: 105.h,
      child: Stack(
        children: [
          // 背景图片
          Positioned.fill(
            child: Image.asset(
              AssetManifest.navigationBackground,
              fit: BoxFit.fill,
            ),
          ),
          // 输入框内容
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 32.h),
            child: SizedBox(
              height: 40.h,
              child: TextField(
                textInputAction: TextInputAction.done,
                controller: _commentController,
                decoration: InputDecoration(
                  hintText: 'Type here...',
                  hintStyle: TextStyle(
                    fontSize: 14.sp,
                    color: ColorPalette.black.withValues(alpha: 0.5),
                  ),
                  filled: true,
                  fillColor: Colors.transparent,
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(25.r),
                    borderSide: BorderSide(
                      color: const Color(0x99999999),
                      width: 1,
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(25.r),
                    borderSide: BorderSide(
                      color: const Color(0x99999999),
                      width: 1,
                    ),
                  ),
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 10.h,
                  ),
                  suffixIcon: GestureDetector(
                    onTap: _handleAddComment,
                    child: Padding(
                      padding: EdgeInsets.all(8.w),
                      child: Image.asset(
                        AssetManifest.send,
                        width: 22.w,
                        height: 22.w,
                      ),
                    ),
                  ),
                ),
                style: TextStyle(fontSize: 14.sp),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 处理举报
  void _handleReport() {
    final dynamic = _getCurrentDynamic();
    if (dynamic == null) return;

    ReportAccusation.raise(
      context,
      targetId: dynamic.id,
      targetType: 'dynamic',
      onReportSubmitted: (reason) {
        _dynamicRoom.deleteDynamic(dynamic.id);
        Navigator.of(context).pop();
      },
    );
  }

  /// 处理举报评论
  void _handleReportComment(String commentId) {
    final dynamic = _getCurrentDynamic();
    if (dynamic == null) return;

    ReportAccusation.raise(
      context,
      targetId: commentId,
      targetType: 'comment',
      onReportSubmitted: (reason) {
        _dynamicRoom.deleteComment(dynamic.id, commentId);
      },
    );
  }

  /// 处理关注
  void _handleFollow(String userId) {
    final currentUser = _userRoom.fetchCurrentUser();
    if (currentUser == null) {
      AuthenticationSpotlight.illuminate(context);
      return;
    }

    final isFollowing = _followRoom.isFollowing(currentUser.id, userId);
    if (isFollowing) {
      _followRoom.performUnfollow(currentUser.id, userId);
    } else {
      _followRoom.performFollow(currentUser.id, userId);
    }
  }

  /// 处理点赞
  void _handleLike(String dynamicId) {
    final currentUser = _userRoom.fetchCurrentUser();
    if (currentUser == null) {
      AuthenticationSpotlight.illuminate(context);
      return;
    }

    _dynamicRoom.toggleLike(dynamicId, currentUser.id);
  }

  /// 处理添加评论
  void _handleAddComment() {
    final currentUser = _userRoom.fetchCurrentUser();
    if (currentUser == null) {
      AuthenticationSpotlight.illuminate(context);
      return;
    }

    if (_commentController.text.trim().isEmpty) return;

    _dynamicRoom.addComment(
      widget.dynamicId,
      currentUser.id,
      _commentController.text.trim(),
    );

    _commentController.clear();
  }

  /// 格式化相对时间
  String _formatRelativeTime(DateTime date) {
    final now = DateTime.now();
    final difference = now.difference(date);

    if (difference.inMinutes < 1) {
      return 'Just now';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes} Minutes Ago';
    } else if (difference.inHours < 24) {
      return '${difference.inHours} ${difference.inHours == 1 ? 'Hour' : 'Hours'} Ago';
    } else if (difference.inDays < 7) {
      return '${difference.inDays} ${difference.inDays == 1 ? 'Day' : 'Days'} Ago';
    } else if (difference.inDays < 30) {
      final weeks = (difference.inDays / 7).floor();
      return '${weeks} ${weeks == 1 ? 'Week' : 'Weeks'} Ago';
    } else if (difference.inDays < 365) {
      final months = (difference.inDays / 30).floor();
      return '${months} ${months == 1 ? 'Month' : 'Months'} Ago';
    } else {
      final years = (difference.inDays / 365).floor();
      return '${years} ${years == 1 ? 'Year' : 'Years'} Ago';
    }
  }

  /// 格式化评论日期
  String _formatCommentDate(DateTime date) {
    return '${date.month}-${date.day}';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      body: Stack(
        children: [
          // 页面内容
          Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(AssetManifest.screenBackground),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: Column(
                children: [
                  // 固定标题栏
                  _buildFixedHeader(),
                  // 内容区域
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          // 媒体轮播
                          _buildMediaCarousel(),
                          // 动态详情卡片
                          _buildDynamicDetailsCard(),
                          // 评论列表
                          _buildCommentsList(),
                          105.h.heightBox, // 为底部输入框留空间
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          // 底部评论输入框
          Positioned(left: 0, right: 0, bottom: 0, child: _buildCommentInput()),
        ],
      ),
    );
  }
}

/// 动态数据模型
class _DynamicData {
  final String id;
  final String userId;
  final String title;
  final String content;
  final List<String> mediaUrls;
  final String mediaType;
  final List<String?> thumbnailUrls;
  final DateTime createdAt;
  final List<String> likes;
  final List comments;
  final String authorName;
  final String authorAvatar;

  _DynamicData({
    required this.id,
    required this.userId,
    required this.title,
    required this.content,
    required this.mediaUrls,
    required this.mediaType,
    required this.thumbnailUrls,
    required this.createdAt,
    required this.likes,
    required this.comments,
    required this.authorName,
    required this.authorAvatar,
  });
}
